package com.fmdj.odr.quartz;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.codingapi.txlcn.common.exception.TCGlobalContextException;
import com.fmdj.common.exception.GlobalException;
import com.fmdj.common.wxpay.MyWXPayConfig;
import com.fmdj.common.wxpay.WXPay;
import com.fmdj.common.wxpay.WXPayConstants;
import com.fmdj.common.wxpay.WXPayUtil;
import com.fmdj.odr.db.dao.OrderProfitsharingDao;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

/*延时分账任务*/
@Component
@Slf4j
public class HandleProfitsharingJob extends QuartzJobBean {

    @Autowired
    private OrderProfitsharingDao orderProfitsharingDao;

    @Autowired
    private MyWXPayConfig myWXPayConfig;
    @Autowired
    private QuartzUtil quartzUtil;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        //从context中拿出业务数据 jobdetail
        Map map = context.getJobDetail().getJobDataMap();
        String uuid = MapUtil.getStr(map, "uuid");
        String driverOpenId = MapUtil.getStr(map, "driverOpenId");
        String payId = MapUtil.getStr(map, "payId");

        //向微信公众平台发起分账请求,在发起分账之前要先查询司机的分账收入以及id
        map = orderProfitsharingDao.searchDriverIncome(uuid);
        if (map==null || map.size() == 0) {
            log.error("查询分账收入失败");
            return;
        }
        Long profitsharingId = MapUtil.getLong(map, "profitsharingId");
        String driverIncome = MapUtil.getStr(map, "driverIncome");

        try{
            //创建微信支付对象
            WXPay wxPay = new WXPay(myWXPayConfig);

            //构造请求参数
            HashMap params = new HashMap<>(){{
                put("mch_id", myWXPayConfig.getMchID());
                put("appid", myWXPayConfig.getAppID());
                put("nonce_str", WXPayUtil.generateNonceStr());
                put("transaction_id", payId);
                put("out_order_no", uuid);
            }};

            //构建接收体
            JSONArray receivers = new JSONArray();
            JSONObject receiver = new JSONObject();
            receiver.set("type", "PERSONAL_OPENID");
            receiver.set("account", driverOpenId);
            //将分账金额由元转成分
//            int amount = Integer.parseInt(NumberUtil.mul(driverIncome, "100").setScale(0, RoundingMode.FLOOR).toString());
            receiver.set("amount", 1);
            receiver.set("description", "给司机的分账");
            receivers.add(receiver);
            params.put("receivers", receivers);

            //构建数字签命
            String sign = WXPayUtil.generateSignature(params, myWXPayConfig.getKey(), WXPayConstants.SignType.HMACSHA256);
            params.put("sign", sign);

            //执行分账请求
            String url = "/pay/profitsharing";
            //无论收还是发 得到的结果都是xml
            String response = wxPay.requestWithCert(url, params, 3000, 3000);
            System.out.println(response);

            //验证响应中的数字签命
            if (WXPayUtil.isSignatureValid(response, myWXPayConfig.getKey(), WXPayConstants.SignType.HMACSHA256)) {
                //验证成功,参数没有被修改
                Map date = wxPay.processResponseXml(response);
                String returnCode = MapUtil.getStr(date, "return_code");
                String resultCode = MapUtil.getStr(date, "result_code");
                if ("SUCCUSS".equals(returnCode) && "SUCCESS".equals(resultCode)) {
                    String status = MapUtil.getStr(date, "status");
                    if ("FINISHED".equals(status)) {
                            //更新分账状态
                        int rows = orderProfitsharingDao.updateProfitSharingStatus(profitsharingId);
                        if (rows!=1) {
                            log.error("更新分账状态失败",new TCGlobalContextException("更新分账状态失败"));
                        }
                    }else if ("PROCESSING".equals(status)){
                        //TODO 创建延时查询分账结果的定时器
                        System.out.println("正在执行分帐中");
                        //创建jobDetail对象再获取jobDataMap然后再放入业务数据
                        JobDetail jobDetail = JobBuilder.newJob(SearchProfitsharingJob.class).build();
                        JobDataMap jobDataMap = jobDetail.getJobDataMap();
                        jobDataMap.put("uuid",uuid);
                        jobDataMap.put("profitsharingId",profitsharingId);
                        jobDataMap.put("payId",payId);

                        DateTime executeTime = new DateTime().offset(DateField.MINUTE, 20);//当前时间的20分钟后执行
                        quartzUtil.addJob(jobDetail, uuid, "查询代驾单分账任务组", executeTime);
                    }
                }else {
                    log.error("微信分账失败",new GlobalException("微信分账失败"));
                }
            }else {
                log.error("验证数字签命失败",new GlobalException("验证数字签命失败"));
            }
        }catch (Exception e){
            log.error("微信分账失败",new GlobalException("微信分账失败"));
        }
    }
}
